class Catalog < ActiveRecord::Base
  #after_create  :fix_access
  #after_save    :fix_access
  
  set_primary_key "catalog_id"
  
  acts_as_tree :order => "name"
           
  belongs_to :owner,
             :class_name => "User",
             :foreign_key => "user_id"
                    
  has_many :pictures,
           :class_name => "Picture",
           :foreign_key => "catalog_id",
           :dependent => true
  
  validates_presence_of :name

  validates_inclusion_of :access,
                         :in => [0, 1, 2]
  
  def is_public?
    return (access == 2)
  end
  
  def is_accessible?(user_id)
    if(user_id != -1)
      return true if owner.id == user_id
      #return true if access == 1 and owner.users_given_friendship.find(user_id)
      if access == 1
        for friends in owner.users_given_friendship
          return true if friends.id == user_id
        end
      end
    end
    return is_public?
  end

  def set_access_up(new_access)
    if access < new_access
      puts "up"
      puts id.to_s + " > old = " + access.to_s + " new = " + new_access.to_s
      # changing to less restrictive access -> altering the path to the root
      if parent
        parent.set_access_up(new_access)
      end
      update_attributes(:access => new_access)
    end
  end
  
  def set_access_down(new_access)
    if access > new_access
      puts "down"
      puts id.to_s + " > old = " + access.to_s + " new = " + new_access.to_s
      # changing to more restrictive access -> altering subtree and pictures
      for child in children
        child.set_access_down(new_access)
      end
      for picture in pictures
        picture.set_access(new_access)  
      end
      update_attributes(:access => new_access)
    end
  end
  
  def destroy_tree
    for child in children
      child.destroy_tree
    end
    for picture in pictures
      picture.destroy
    end
    destroy
  end
  
  def fix_access
    puts id.to_s + " fix access -> " + access.to_s
    for child in children
      child.set_access_down(access) if child.access > access
    end
    for picture in pictures
      picture.set_access(access) if picture.access > access
    end
    if parent
      parent.set_access_up(access) if parent.access < access
    end
  end
  
  def get_path(depth)
    return [owner.root_catalog] if depth == 0
    if parent
      val = parent.get_path(depth - 1) << self
    else
      val = [self]
    end
    return val
  end
  
  def validate
    if parent
      for child in parent.children
        if child.name == name and self != child
          errors.add(:name, " is already taken")
          break
        end
      end
    end
  end
end
